package cn.hy.batch.reader;

import cn.hy.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Slf4j
public class ItemReaderXmlDemo {

    //注入任务对象工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定,注入step对象的factory
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    //创建Job对象
    @Bean
    public Job jobDemoxml() {
        return jobBuilderFactory.get("jobDemoxml")
                .start(step_xml())
                .build();
    }

    //创建Step对象
    @Bean
    public Step step_xml() {
        return stepBuilderFactory.get("step_xml")
                .<User, User>chunk(2)
                .reader(xmlreader())
                .writer(new ItemWriter<User>() {
                    @Override
                    public void write(List<? extends User> list) throws Exception {
                        System.out.println("输出list");
                        for (User user : list) {
                            System.out.println(user);
                        }
                    }
                })
                .build();
    }

    @Bean
    public StaxEventItemReader<User> xmlreader() {
        StaxEventItemReader reader = new StaxEventItemReader();
        reader.setResource(new ClassPathResource("user.xml"));
        reader.setFragmentRootElementName("user");//设置根标签,指的是数据标签<user>

        XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();//将xml转对象
        Map<String, Class> map = new HashMap<>();
        map.put("user", User.class);
        xStreamMarshaller.setAliases(map);

        reader.setUnmarshaller(xStreamMarshaller);//xml的转换器
        return reader;
    }
}
